package com.ft.admix.bd.adapter;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.DialogInterface;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.ft.adbix.utils.universalimageloader.core.ImageLoader;
import com.kwad.sdk.api.KsAdVideoPlayConfig;
import com.kwad.sdk.api.KsImage;
import com.kwad.sdk.api.KsNativeAd;
import com.ft.admix.ad.MixCustomNativeAd;
import com.kwad.sdk.api.model.AdSourceLogoType;
import com.kwad.sdk.api.model.InteractionType;
import com.kwad.sdk.api.model.KsNativeConvertType;
import com.kwad.sdk.api.model.MaterialType;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CustomKsNativeAd extends MixCustomNativeAd {
    KsNativeAd ksNativeAd;
    Activity mActivity;

    public CustomKsNativeAd(Activity activity, KsNativeAd ksNativeAd) {
        this.ksNativeAd = ksNativeAd;
        this.mActivity = activity;

    }

    @Override
    public void render(ViewGroup viewGroup) {
        super.render(viewGroup);
        // 快手原生广告的渲染
        if (ksNativeAd != null) {

            // 快手SDK的渲染方法可能不同，需要根据实际SDK文档调整
        }
    }

    @Override
    public View getExpressView(ViewGroup viewGroup) {
        viewGroup.removeAllViews();
        View adView;
        // 判断广告素材类型
        switch (ksNativeAd.getMaterialType()) {
            case MaterialType.VIDEO:
                // 视频素材，渲染自定义的视频广告
                adView = getVideoItemView(viewGroup, ksNativeAd);
                break;
            case MaterialType.SINGLE_IMG:
                // 单图素材，渲染自定义的单图广告
                adView = getSingleImageItemView(viewGroup, ksNativeAd);
                break;
            case MaterialType.GROUP_IMG:
                // 组图素材，渲染自定义的组图广告
                adView = getGroupImageItemView(viewGroup, ksNativeAd);
                break;
            case MaterialType.UNKNOWN:
            default:
                adView = getNormalItemView(viewGroup);

        }
        return adView;
    }

    /**
     * 使用SDK渲染的播放控件, 直播 or 普通视频
     */
    protected View getVideoItemView(ViewGroup parent, KsNativeAd ksNativeAd) {
        View convertView =
                LayoutInflater.from(parent.getContext()).inflate(R.layout.native_item_video, parent, false);
        AdVideoViewHolder videoViewHolder = new AdVideoViewHolder(convertView);

        ksNativeAd.setVideoPlayListener(new KsNativeAd.VideoPlayListener() {
            @Override
            public void onVideoPlayReady() {

//                ToastUtil.showToast(getApplicationContext(), "onVideoPlayReady");
//                LogUtils.recodeCallback(LogUtils.SCENE_NATIVE_PRE, "onVideoPlayReady");
            }

            @Override
            public void onVideoPlayStart() {
                callVideoStart();
//                ToastUtil.showToast(getApplicationContext(), "onVideoPlayStart");
//                LogUtils.recodeCallback(LogUtils.SCENE_NATIVE_PRE, "onVideoPlayStart");
            }

            @Override
            public void onVideoPlayComplete() {
                callVideoCompleted();
//                ToastUtil.showToast(getApplicationContext(), "onVideoPlayComplete");
//                LogUtils.recodeCallback(LogUtils.SCENE_NATIVE_PRE, "onVideoPlayComplete");
            }

            @Override
            public void onVideoPlayError(int what, int extra) {
                callVideoError(what,String.valueOf(extra));
//                ToastUtil.showToast(getApplicationContext(), "onVideoPlayError");
//                LogUtils.recodeCallback(LogUtils.SCENE_NATIVE_PRE, "onVideoPlayError");
            }

            @Override
            public void onVideoPlayPause() {
                callVideoPause();
//                ToastUtil.showToast(getApplicationContext(), "onVideoPlayPause");
//                LogUtils.recodeCallback(LogUtils.SCENE_NATIVE_PRE, "onVideoPlayPause");
            }

            @Override
            public void onVideoPlayResume() {
                callVideoResume();
//                ToastUtil.showToast(getApplicationContext(), "onVideoPlayResume");
//                LogUtils.recodeCallback(LogUtils.SCENE_NATIVE_PRE, "onVideoPlayResume");
            }
        });

        // SDK默认渲染的视频view
        KsAdVideoPlayConfig videoPlayConfig = new KsAdVideoPlayConfig.Builder()
                .dataFlowAutoStart(true) // 流量下自动播放
                .videoAutoPlayType(
                        KsAdVideoPlayConfig.VideoAutoPlayType.AUTO_PLAY) // 设置在有wifi
                // 时视频自动播放，当与dataFlowAutoStart()同时设置时，以最后一个传入的值为准
                .build();
        View videoView = ksNativeAd.getVideoView(mActivity, videoPlayConfig);
        if (videoView != null && videoView.getParent() == null) {
            videoViewHolder.mAdVideoContainer.removeAllViews();
            videoViewHolder.mAdVideoContainer.addView(videoView);
        }

        // 获取扭摇view
        if (ksNativeAd.enableRotate()) {
            View rotateView = ksNativeAd.getRotateView(mActivity);
            if (rotateView != null) {
                FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                layoutParams.gravity = Gravity.CENTER;
                videoViewHolder.mAdVideoContainer.addView(rotateView, layoutParams);
            }
        }
        // 设置广告数据
        bindCommonData((ViewGroup) convertView, videoViewHolder, ksNativeAd);

        return convertView;
    }

    /**
     * 使用媒体自己渲染的播放控件
     */
    protected View getVideoItemView2(ViewGroup parent, KsNativeAd ksNativeAd) {
        View convertView =
                LayoutInflater.from(parent.getContext()).inflate(R.layout.native_item_video, parent, false);
        AdVideoViewHolder viewHolder = new AdVideoViewHolder(convertView);

        // 设置广告数据
        bindCommonData((ViewGroup) convertView, viewHolder, ksNativeAd);

        /** 媒体也可以自渲染视频view start **/
        // 获取视频地址
        String videoUrl = ksNativeAd.getVideoUrl();
        // 获取视频时长
        int videoDuration = ksNativeAd.getVideoDuration();
        // 获取视频封面图片
        KsImage ksImage = ksNativeAd.getVideoCoverImage();

        // 特别注意，视频播放需要客户自渲染，所以需要客户在合适时机掉如下方法进行打点，用于统计视频观看时长
        // 1.请在视频播放开始时调用此方法（每次从0秒开始播放，暂停恢复除外）
        ksNativeAd.reportAdVideoPlayStart();
//    // 2.请在视频播放结束时调用此方法（每次播放到最后1s，暂停恢复除外）
        ksNativeAd.reportAdVideoPlayEnd();
        /** 自渲染视频view end **/
        return convertView;
    }

    protected View getSingleImageItemView(ViewGroup parent, KsNativeAd ksNativeAd) {
        View convertView =
                LayoutInflater.from(parent.getContext()).inflate(R.layout.native_item_single_image, parent, false);
        AdSingleImageViewHolder viewHolder = new AdSingleImageViewHolder(convertView);
        bindCommonData((ViewGroup) convertView, viewHolder, ksNativeAd);

        // 获取图片资源
        if (ksNativeAd.getImageList() != null && !ksNativeAd.getImageList().isEmpty()) {
            KsImage image = ksNativeAd.getImageList().get(0);
            if (image != null && image.isValid()) {
                ImageLoader.getInstance().displayImage(image.getImageUrl(),viewHolder.mAdImage);
            }
        }
        return convertView;
    }

    protected View getGroupImageItemView(ViewGroup parent, KsNativeAd ksNativeAd) {
        View convertView =
                LayoutInflater.from(parent.getContext()).inflate(R.layout.native_item_group_image, parent, false);
        AdGroupImageViewHolder viewHolder = new AdGroupImageViewHolder(convertView);
        bindCommonData((ViewGroup) convertView, viewHolder, ksNativeAd);

        // 获取图片资源
        List<KsImage> ksImageList = ksNativeAd.getImageList();
        if (ksImageList != null && !ksImageList.isEmpty()) {
            for (int i = 0; i < ksImageList.size(); i++) {
                KsImage image = ksNativeAd.getImageList().get(i);
                if (image != null && image.isValid()) {
                    if (i == 0) {
                        ImageLoader.getInstance().displayImage(image.getImageUrl(),viewHolder.mAdImageLeft);
                    } else if (i == 1) {
                        ImageLoader.getInstance().displayImage(image.getImageUrl(),viewHolder.mAdImageMid);
                    } else if (i == 2) {
                        ImageLoader.getInstance().displayImage(image.getImageUrl(),viewHolder.mAdImageRight);
                    }
                }
            }
        }
        return convertView;
    }

    @SuppressLint("DefaultLocale")
    protected View getNormalItemView(ViewGroup parent) {
        View convertView =
                    LayoutInflater.from(parent.getContext()).inflate(R.layout.native_item_normal, parent, false);
        NormalViewHolder normalViewHolder = new NormalViewHolder(convertView);
        normalViewHolder.textView.setText("没有广告");
        return convertView;
    }

    private void bindCommonData(ViewGroup convertView, AdBaseViewHolder adBaseViewHolder,
                                final KsNativeAd ad) {
        // 点击转换view的集合，传入的view点击时会触发转换操作：app下载， 打开h5页面
        Map<View, Integer> clickViewMap = new HashMap<>();
        clickViewMap.put(adBaseViewHolder.mAdContainer, KsNativeConvertType.CONVERT);
        clickViewMap.put(adBaseViewHolder.mAdConvertBtn, KsNativeConvertType.CONVERT);
        clickViewMap.put(adBaseViewHolder.mAdIcon, KsNativeConvertType.CONVERT);
        clickViewMap.put(adBaseViewHolder.mAdName, KsNativeConvertType.SHOW_DOWNLOAD_TIPS_DIALOG);
        clickViewMap.put(adBaseViewHolder.mAdDes, KsNativeConvertType.SHOW_DOWNLOAD_TIPS_DIALOG);
        clickViewMap.put(adBaseViewHolder.mAdDesc, KsNativeConvertType.SHOW_DOWNLOAD_TIPS_DIALOG);

        if (adBaseViewHolder instanceof AdSingleImageViewHolder) {
            clickViewMap.put(((AdSingleImageViewHolder) adBaseViewHolder).mAdImage,
                    KsNativeConvertType.CONVERT);
        }
        //视频需要支持点击请传入视频的view 转化行为由sdk控制
        if (adBaseViewHolder instanceof AdVideoViewHolder) {
            clickViewMap.put(((AdVideoViewHolder) adBaseViewHolder).mAdVideoContainer.getChildAt(0),
                    KsNativeConvertType.CONVERT_SLIDE);
        }

        // 如果是自定义弹窗，请使用下面的配置
        // 注册View的点击，点击后触发转化
        ad.registerViewForInteraction(mActivity, convertView, clickViewMap,
                new KsNativeAd.AdInteractionListener() {
                    @Override
                    public void onAdClicked(View view, KsNativeAd ad) {
                        if (ad != null) {
                            callAdClick();
//                            ToastUtil.showToast(mContext, "广告" + ad.getAppName() + "被点击");
//                            LogUtils.recodeCallback(LogUtils.SCENE_NATIVE_PRE, "onAdClicked");
//                            /**********DevelopCode Start***********/
//                            if (mIsBidFailed) {
//                                //模拟竞价失败，展示其他广告时点击上报
//                                testBidFailedClickAndShowReport(ad, AdActionType.CLICK);
//                            }
//                            /**********DevelopCode End***********/
                        }
                    }

                    @Override
                    public void onAdShow(KsNativeAd ad) {
                        if (ad != null) {
                            callAdShow();
//                            ToastUtil.showToast(mContext, "广告" + ad.getAppName() + "展示");
//                            LogUtils.recodeCallback(LogUtils.SCENE_NATIVE_PRE, "onAdShow");
                            /**********DevelopCode Start***********/
//                            if (mIsBidFailed) {
//                                //模拟竞价失败，展示其他广告时曝光上报
//                                testBidFailedClickAndShowReport(ad, AdActionType.SHOW);
//                            }
                            /**********DevelopCode End***********/
                        }
                    }

                    /*
                     *  @return  返回为true, 则只会给媒体弹出回调，SDK的默认弹窗逻辑不会执行
                     * @return  返回为true 返回为 false, 则使用SDK默认的合规弹窗。
                     * 弹出弹窗dialog后， 用户确认下载，则媒体需要回调 OnClickListener.onClick(dialog, DialogInterface
                     * .BUTTON_POSITIVE)
                     * 弹出弹窗dialog后， 用户点击取消，则媒体需要回调 OnClickListener.onClick(dialog, DialogInterface
                     * .BUTTON_NEGATIVE)
                     * */
                    @Override
                    public boolean handleDownloadDialog(DialogInterface.OnClickListener clickListener) {
//                        LogUtils.recodeCallback(LogUtils.SCENE_NATIVE_PRE, "handleDownloadDialog");
                        return false;
                    }

                    @Override
                    public void onDownloadTipsDialogShow() {
//                        ToastUtil.showToast(mContext, "广告展示下载合规弹窗");
//                        LogUtils.recodeCallback(LogUtils.SCENE_NATIVE_PRE, "onDownloadTipsDialogShow");
                    }

                    @Override
                    public void onDownloadTipsDialogDismiss() {
//                        ToastUtil.showToast(mContext, "广告关闭下载合规弹窗");
//                        LogUtils.recodeCallback(LogUtils.SCENE_NATIVE_PRE, "onDownloadTipsDialogDismiss");
                    }
                });

        /**********DevelopCode Start***********/
//        logAdForTest(ad);
        /**********DevelopCode End***********/

//        // 其他数据
//        Log.d("AppInfo", "应用名字 = " + ad.getAppName());
//        Log.d("AppInfo", "应用包名 = " + ad.getAppPackageName());
//        Log.d("AppInfo", "应用版本 = " + ad.getAppVersion());
//        Log.d("AppInfo", "开发者 = " + ad.getCorporationName());
//        Log.d("AppInfo", "包大小 = " + ad.getAppPackageSize());
//        Log.d("AppInfo", "隐私条款链接 = " + ad.getAppPrivacyUrl());
//        Log.d("AppInfo", "权限信息 = " + ad.getPermissionInfo());
//        Log.d("AppInfo", "权限信息链接 = " + ad.getPermissionInfoUrl());
//        Log.d("AppInfo", "功能介绍 = " + ad.getIntroductionInfo());
//        Log.d("AppInfo", "功能介绍链接 = " + ad.getIntroductionInfoUrl());
//        // 获取app的评分，取值范围0~5.0
//        Log.d("AppInfo", "应用评分 = " + ad.getAppScore());
//        // 获取app下载次数文案，例如：800W此下载，自行渲染。
//        Log.d("AppInfo", "app下载次数文案 = " + ad.getAppDownloadCountDes());

        // 广告描述
        adBaseViewHolder.mAdDes.setText(ad.getAdDescription());
        String adIconUrl = ad.getAppIconUrl();
        // 广告icon
        if (!TextUtils.isEmpty(adIconUrl)) {
            ImageLoader.getInstance().displayImage(adIconUrl,adBaseViewHolder.mAdIcon);
            adBaseViewHolder.mAdIcon.setVisibility(View.VISIBLE);
        } else {
            adBaseViewHolder.mAdIcon.setVisibility(View.GONE);
        }
        // 广告转化文案
        adBaseViewHolder.mAdConvertBtn.setText(ad.getActionDescription());
        // 广告名称
        if (ad.getInteractionType() == InteractionType.DOWNLOAD) {
            adBaseViewHolder.mAdName.setText(ad.getAppName());
            // 下载类型的可以设置下载监听
//            bindDownloadListener(adBaseViewHolder, ad);
        } else {
            adBaseViewHolder.mAdName.setText(ad.getProductName());
        }
        // 广告描述
        adBaseViewHolder.mAdDesc.setText(ad.getAdDescription());

        // 不喜欢
        adBaseViewHolder.mDislikeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                ToastUtil.showToast(mContext, "广告" + ad.getAppName() + "不喜欢点击");
            }
        });
        // 广告来源
        String adSource = ad.getAdSource();
        boolean grayMode = true; // 开发者可根据实际需要调整
        if (TextUtils.isEmpty(adSource)) {
            adBaseViewHolder.mAdSourceDesc.setVisibility(View.GONE);
            adBaseViewHolder.mAdSourceDesc.setText("");
            adBaseViewHolder.mAdLogoIcon.setVisibility(View.GONE);
        } else {
            ImageLoader.getInstance().displayImage(ad.getAdSourceLogoUrl(grayMode ? AdSourceLogoType.GREY : AdSourceLogoType.NORMAL),adBaseViewHolder.mAdLogoIcon);
            adBaseViewHolder.mAdSourceDesc.setTextColor(grayMode ? 0xFF9C9C9C : 0x99FFFFFF);
            adBaseViewHolder.mAdSourceDesc.setText(adSource);
        }
    }

    private static class NormalViewHolder {
        TextView textView;

        NormalViewHolder(View convertView) {
            this.textView = convertView.findViewById(R.id.tv);
        }
    }

    private static class AdSingleImageViewHolder extends AdBaseViewHolder {
        ImageView mAdImage;

        AdSingleImageViewHolder(View convertView) {
            super(convertView);
            mAdImage = convertView.findViewById(R.id.ad_image);
        }
    }

    private static class AdGroupImageViewHolder extends AdBaseViewHolder {
        ImageView mAdImageLeft;
        ImageView mAdImageMid;
        ImageView mAdImageRight;

        AdGroupImageViewHolder(View convertView) {
            super(convertView);
            mAdImageLeft = convertView.findViewById(R.id.ad_image_left);
            mAdImageMid = convertView.findViewById(R.id.ad_image_mid);
            mAdImageRight = convertView.findViewById(R.id.ad_image_right);
        }
    }

    private static class AdVideoViewHolder extends AdBaseViewHolder {
        FrameLayout mAdVideoContainer;

        AdVideoViewHolder(View convertView) {
            super(convertView);
            mAdVideoContainer = convertView.findViewById(R.id.video_container);
        }
    }

    private static class AdBaseViewHolder {
        TextView mAdDes;
        ImageView mAdIcon;
        TextView mAdName;
        TextView mAdDesc;
        TextView mAdConvertBtn;
        ImageView mDislikeBtn;
        ImageView mAdLogoIcon;
        TextView mAdSourceDesc;
        ViewGroup mAdContainer;

        AdBaseViewHolder(View convertView) {
            mAdDes = convertView.findViewById(R.id.ad_desc);
            mAdIcon = convertView.findViewById(R.id.app_icon);
            mAdName = convertView.findViewById(R.id.app_title);
            mAdDesc = convertView.findViewById(R.id.app_desc);
            mAdConvertBtn = convertView.findViewById(R.id.app_download_btn);
            mDislikeBtn = convertView.findViewById(R.id.ad_dislike);
            mAdLogoIcon = convertView.findViewById(R.id.ksad_logo_icon);
            mAdSourceDesc = convertView.findViewById(R.id.ksad_logo_text);
            mAdContainer = convertView.findViewById(R.id.ad_container);
        }
    }

} 